<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-07 14:56:11
 * @LastEditTime: 2022-04-19 21:12:54
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 录屏
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>录屏</title>
</head>

<body>
  <button id="btn">开始录制</button>
  <video controls width="400px" height="300px"></video>
</body>
<script>
  const btn = document.querySelector('#btn')
  btn.addEventListener('click', async () => {
     let stream = null
    try {
       stream = await navigator.mediaDevices.getDisplayMedia({
        video: true
      })
    } catch (e) {
      console.log('出错了', e);
    }

    const mime = MediaRecorder.isTypeSupported("video/webm\;codecs=vp9") ? "video/webm\;codecs=vp9" : 'video/webm'
    let mediaRecorder = new MediaRecorder(stream, {
      mimeType: mime,
      ignoreMutedMedia:true
    })
    let chunks = []
    mediaRecorder.addEventListener('dataavailable', (e) => {
      console.log('开始');
      chunks.push(e.data)
    })
    mediaRecorder.addEventListener('stop', () => {
      console.log('停止');
      const blob = new Blob(chunks, {
        type: chunks[0].type
      })
      const url = URL.createObjectURL(blob)
      const video = document.querySelector('video')
      video.src = url

      const a = document.createElement('a')
      a.href = url
      a.download = 'video.webm'
      a.click()
    })
    mediaRecorder.start()
  })


</script>

</html>